class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def getLonelyNodes(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        out = []

        def search(node):
            if node.left:
                if node.right:
                    search(node.left)
                    search(node.right)
                else:
                    out.append(node.left.val)
                    search(node.left)
            else:
                if node.right:
                    out.append(node.right.val)
                    search(node.right)

        search(root)
        return out